package com.zzr.zzrbackend.service.Impl;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.zzr.zzrbackend.constant.Constant;
import com.zzr.zzrbackend.mapper.AuthenticationCodeMapper;
import com.zzr.zzrbackend.pojo.domain.AuthenticationCode;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.param.SeedCodeParam;
import com.zzr.zzrbackend.pojo.dto.result.NoData;
import com.zzr.zzrbackend.service.AuthenticationService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Resource
    private AuthenticationCodeMapper authenticationCodeMapper;

    @Override
    public CommonResult<NoData> seedCode(SeedCodeParam seedCodeParam) throws Exception {

        //获取当前时间戳
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        //生成4位随机数
        Random random = new Random();
        Integer code = random.nextInt(9999 - 1000 + 1) + 1000;

        //进入短信阶段
        String errorMessage = null;
        SendSmsResponse sendSmsResponse = null;
        com.aliyun.dysmsapi20170525.Client client = AuthenticationServiceImpl.createClient(Constant.accessKeyId
                , Constant.accessKeySecret);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest =
                new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                        .setSignName(Constant.signName)
                        .setTemplateCode(Constant.templateCode)
                        .setPhoneNumbers(seedCodeParam.getPhone())
                        .setTemplateParam("{\"code\":\"" + code + "\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            errorMessage = error.message;
        }
        if (errorMessage == null && "OK".equals(Objects.requireNonNull(sendSmsResponse).body.message)) {
            //将手机号和code存入数据库
            //先判断数据库是否存在该手机号数据
            List<AuthenticationCode> authenticationCodes =
                    authenticationCodeMapper.selectAllByPhone(seedCodeParam.getPhone());
            if (authenticationCodes.size() == 0) {
                authenticationCodeMapper.insert(seedCodeParam.getPhone(), code, timestamp.getTime() / 1000);
            } else {
                authenticationCodeMapper.updateCodeByPhone(seedCodeParam.getPhone(), code, timestamp.getTime() / 1000);
            }
            return CommonResult.success();
        } else if (errorMessage != null) {
            return CommonResult.fail(errorMessage);
        } else {
            return CommonResult.fail(sendSmsResponse.body.message);
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
